import 'package:dio/dio.dart';
import 'package:flutter_enjoy/constants/index.dart';
import 'package:flutter_enjoy/utils/toast.dart';

class RequestDio {
  final Dio _dio = Dio();

  RequestDio() {
    // 设置请求根数据
    _dio.options.baseUrl = GlobalVariable.BASE_URL;
    // 设置请求的连接超时时间
    _dio.options.connectTimeout =
        const Duration(seconds: GlobalVariable.TIMEOUT);
    // 设置请求的接收超时时间
    _dio.options.receiveTimeout =
        const Duration(seconds: GlobalVariable.TIMEOUT);

    // 设置请求头
    // _dio.options.headers = {
    //   'Content-Type': 'application/json',
    //   'Accept': 'application/json',
    // };
    // 拦截器4
    _interceptors();
  }
  // 拦截器
  void _interceptors() {
    // 请求拦截器
    _dio.interceptors.add(InterceptorsWrapper(
      // 请求拦截器
      onRequest: (options, handler) {
        // 自动添加token
        handler.next(options);
      },
      // 响应拦截器
      onResponse: (response, handler) {
        // 响应拦截器
        handler.next(response);
      },
      // 错误拦截器
      onError: (error, handler) {
        PromptAction.showError(error.response?.data['message'] ?? '请求失败');
        // 错误拦截器
        handler.next(error);
      },
    ));
  }

  // 请求二次封装get
  Future get(String url, {Map<String, dynamic> params = const {}}) async {
    final response = await _dio.get(url, queryParameters: params);
    return _handleResponsive(response);
  }

  // 请求二次封装post
  Future post(String url, {Map<String, dynamic> data = const {}}) async {
    final response = await _dio.post(url, data: data);
    return _handleResponsive(response);
  }

  // 请求二次封装put
  Future put(String url, {Map<String, dynamic> data = const {}}) async {
    final response = await _dio.put(url, data: data);
    return _handleResponsive(response);
  }

  // 请求二次封装delete
  Future delete(String url, {Map<String, dynamic> data = const {}}) async {
    final response = await _dio.delete(url, data: data);
    return _handleResponsive(response);
  }

  // 请求二次封装patch
  Future patch(String url, {Map<String, dynamic> data = const {}}) async {
    final response = await _dio.patch(url, data: data);
    return _handleResponsive(response);
  }

  _handleResponsive(Response response) {
    if (response.data['code'] == GlobalVariable.SUCCESS_CODE) {
      return response.data['data'];
    } else {
      // 业务状态码错误
      PromptAction.showError(response.data['message']);
    }
    throw Exception(response.data['message']);
  }
}

final requestDio = RequestDio();
